package com.binarycube.webserver;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.handler.ErrorHandler;

public class ServerErrorHandler extends ErrorHandler {
	static Logger log = Logger.getLogger(ServerErrorHandler.class.getName());
	

	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		if (! response.isCommitted()) {
			response.setContentType("text/html");
			
			 String reason=(response instanceof Response)?((Response)response).getReason():"";
			 String uri= request.getRequestURI();
			 String reference = "" + UUID.randomUUID().toString().substring(0,8);
			 
			 StringBuilder buffer = new StringBuilder();
			 buffer.append("<b>Code:</b> " +response.getStatus() +"<br>");
			 buffer.append("<b>Details:</b> " + reason +"<br>");
			 buffer.append("<b>Request:</b> " + uri +"<br>");
			 buffer.append("<b>Ref:</b> " +reference +"<br>");
			 String template = FileUtils.readFileToString(new File("etc/ErrorPage.txt"));
			 response.getWriter().print(template.replace("{content}", buffer.toString()));
				
				
			 
			 logError(request, reference, response.getStatus(), reason);
		}
		response.setStatus(HttpServletResponse.SC_OK);
		response.flushBuffer();
		baseRequest.setHandled(true);
	}

	private void logError(HttpServletRequest request, String reference, int status, String message){
		log.info("Error report for:" + reference + ", Status:" + status + " Message:" + message + " request:" + request.getRequestURI());
		 Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception");
		 while (th!=null) {
			 log.error("Error(" + reference +"):", th);
			 th =th.getCause();
		 }
	}
	
}
